package com.masterrabbit.controller;

import com.alibaba.fastjson.JSON;
import com.masterrabbit.domain.Merchants;
import com.masterrabbit.mapper.ImagesMapper;
import com.masterrabbit.service.MerchantsService;
import com.masterrabbit.utils.MapMarker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/geo")
public class GeoController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MerchantsService merchantsService;
    @Autowired
    private ImagesMapper imagesMapper;

    @RequestMapping("/add")
    void geoadd(@RequestParam double longitude,
                @RequestParam double latitude,
                @RequestParam String merchantsId) {
        GeoOperations<String, String> geo = stringRedisTemplate.opsForGeo();
        Point point = new Point(longitude, latitude);
        RedisGeoCommands.GeoLocation<String> geoLocation =
                new RedisGeoCommands.GeoLocation<>(merchantsId, point);
        geo.add("merchants", geoLocation);
    }

    //删除
    @RequestMapping("/del")
    void geodel() {
        GeoOperations<String, String> geo = stringRedisTemplate.opsForGeo();
        geo.remove("merchants");
    }

    /**
     * 根据经纬度查询附近的位置
     *
     * @param longitude 目标经度
     * @param latitude  目标纬度
     * @param radius    半径(米)
     * @return 附近位置的marker列表
     */
    @GetMapping("/radius")
    @ResponseBody
    public List<MapMarker> georadius(
            @RequestParam double longitude,
            @RequestParam double latitude,
            @RequestParam double radius) {

        // 创建 georadius 命令参数
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending()
                .limit(10);

        // 执行 georadius 查询
        GeoResults<RedisGeoCommands.GeoLocation<String>> locationGeoResults = stringRedisTemplate.opsForGeo()
                .radius("merchants",
                        new Circle(new Point(longitude, latitude),
                                new Distance(radius, RedisGeoCommands.DistanceUnit.METERS)),
                        args);

        // 将结果转化为 MapMarker 列表
        List<MapMarker> markers = new ArrayList<>();
        long idCounter = 1; // 用于生成唯一的 marker id
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> geoResult : locationGeoResults.getContent()) {
            RedisGeoCommands.GeoLocation<String> geoLocation = geoResult.getContent();
            Point point = geoLocation.getPoint();


            // 创建 marker 对象
            MapMarker marker = new MapMarker(
                    idCounter++,
                    point.getY(), // 纬度
                    point.getX(), // 经度
                    geoLocation.getName(), // 标题
                    35, // 宽度
                    35, // 高度
                    "expand", // 动画
                    null,
                    geoResult.getDistance().getValue() + geoResult.getDistance().getUnit()
            );
            System.out.println(JSON.toJSONString(marker));
            Merchants merchants = merchantsService.selectMerchants(Long.parseLong(geoLocation.getName()));

            // 创建 callout 对象
            MapMarker.Callout callout = new MapMarker.Callout(
                    "附近门店>",
                    "#f0f9ff",
                    8,
                    12,
                    "center",
                    "ALWAYS"
            );

            if (merchants != null) {
                marker.setPhoneNumber(merchants.getPhoneNumber());
                marker.setBusinessHours(merchants.getBusinessHours());
                //读取图片
                System.out.println(merchants.getBusinessLicenseImageId());
                List<String> images = imagesMapper.selectByProductId(merchants.getBusinessLicenseImageId());
                marker.setImages(images);
                marker.setDetailedAddress(merchants.getDetailedAddress());
                callout.setContent(merchants.getShopName());
                marker.setTitle(merchants.getShopName());
                marker.setCallout(callout);
                marker.setMerchantId(merchants.getMerchantId());
                markers.add(marker);
            }
        }
        return markers;
    }
}